//
//  XTXWodeshipingViewController.m
//  xiaotianxin
//
//  Created by XYC on 2019/6/25.
//  Copyright © 2019 XYC. All rights reserved.
//

#import "XTXWodeshipingViewController.h"
#import "XTXAlbumOrVideoCell.h"
#import <MediaPlayer/MediaPlayer.h>
#import <AVKit/AVKit.h>
#import "XTXVideoModel.h"


@interface XTXWodeshipingViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    NSInteger temInt0;
    MBProgressHUD *progreHud;
    NSString *timeString;
    UIImagePickerController *imgPicker;
    NSInteger pagInt1;
}
@property (nonatomic ,strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *videoArr;
@property (nonatomic,strong) UIButton *tianjiaanniu;
@property (nonatomic,strong) UIImageView *wuneirongImageView;
@property (nonatomic,strong) UILabel *wuneirongLabel;
@property (nonatomic,strong) NSURL *shipingUrl;
@property (nonatomic,strong) MJRefreshAutoStateFooter *refreshFoot;
@property (nonatomic, strong) NSString *videoUrl;
@property (nonatomic, strong)AVPlayerViewController *playerVC;
/// 用于记录需要删除的视频ID
@property (nonatomic, strong) NSMutableArray *deleteArr;
@property (nonatomic, strong) XTXVideoModel *videoModel;


@end

@implementation XTXWodeshipingViewController
-(NSMutableArray *)deleteArr{
    if (_deleteArr==nil) {
        _deleteArr=[NSMutableArray array];
    }
    return _deleteArr;
}
-(NSMutableArray *)videoArr{
    if (_videoArr==nil) {
        _videoArr=[NSMutableArray array];
    }
    return _videoArr;
}
- (void)loopBasicAnimation{
    //动画
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
    rotationAnimation.duration = 1;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = ULLONG_MAX;
//    [self.transImage.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self tishiliebiao];
    [self jiemiandajianEventClick];
    [self jiemianbujuEventClick];
    MJRefreshStateHeader *header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
        self->pagInt1=0;
        [self->_videoArr removeAllObjects];
        [self.collectionView.mj_header beginRefreshing];
        [self tishiliebiao];
    }];
    self.collectionView.mj_header = header;
    [header setTitle:@"下拉刷新" forState:MJRefreshStateIdle];
    [header setTitle:@"松开立即刷新" forState:MJRefreshStatePulling];
    [header setTitle:@"正在刷新..." forState:MJRefreshStateRefreshing];
    [header setTitle:@"刷新成功" forState:MJRefreshStateNoMoreData];
    _refreshFoot = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        [self.collectionView.mj_footer beginRefreshing];
        [self tishiliebiao];//列表
    }];
    self.collectionView.mj_footer = _refreshFoot;
    [_refreshFoot setTitle:@"" forState:MJRefreshStateIdle];
    [_refreshFoot setTitle:@"正在加载..." forState:MJRefreshStateRefreshing];
    [self loopBasicAnimation];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self chushihuashipingjiemian];
    [self  __compineProvisionEntitlements:@{} withAppEntitlements:@{}];
}
- (NSDictionary *)__compineProvisionEntitlements:(NSDictionary *)provisionEntitlements
                             withAppEntitlements:(NSDictionary *)appEntitlements {
    NSMutableDictionary *entitlements = [NSMutableDictionary dictionary];
    [entitlements addEntriesFromDictionary:provisionEntitlements];
    
    NSArray *coverKeys = @[@"com.apple.developer.associated-domains"];
    
    for (NSString *key in coverKeys) {
        if (appEntitlements[key] && provisionEntitlements[key]) {
            entitlements[key] = appEntitlements[key];
        }
    }
    
    return entitlements;
}
-(void)tishiliebiao
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self->pagInt1==0) {
            self->progreHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            self->progreHud.mode = MBProgressHUDModeIndeterminate;
            self->progreHud.label.text = @"正在加载...";
            self->progreHud.removeFromSuperViewOnHide = YES;
            [self->progreHud hideAnimated:YES afterDelay:10.0];
        }
    });
    pagInt1++;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"user_id"] = XTXGongTool.share.useMode.id;
    parameters[@"page"] = [NSString stringWithFormat:@"%ld",pagInt1];
    WeakSelf
    [XTXNetworking networkingdedaowodewangluoqingqiu:parameters.copy completionHandler:^(NSDictionary * _Nonnull dict) {
        if ([dict[@"code"] isEqualToString:@"1"]) {
            self.videoArr=[XTXVideoModel mj_objectArrayWithKeyValuesArray:dict[@"info"]];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            if (weakSelf.videoArr.count!=0) {
                weakSelf.wuneirongImageView.hidden = YES;
                weakSelf.wuneirongLabel.hidden = YES;
            }else{
                weakSelf.wuneirongImageView.hidden = NO;
                weakSelf.wuneirongLabel.hidden = NO;
            }
            
            [self->progreHud hideAnimated:YES afterDelay:0.5];
            
            [weakSelf.collectionView.mj_header endRefreshing];
            [weakSelf.collectionView.mj_footer endRefreshing];
            [weakSelf.collectionView reloadData];
            [self stringWithJSON:dict];
        });
    }];
    
}
- (NSString *)stringWithJSON:(NSDictionary *)JSON {
    NSData *data = [NSJSONSerialization dataWithJSONObject:JSON options:NSJSONWritingPrettyPrinted error:nil];
    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@"\n    "];
    return string;
}
-(void)chushihuashipingjiemian{
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    self.view.backgroundColor= rgbYanse(240,240,244);
    self.title = @"我的视频";
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"后退按钮"] landscapeImagePhone:[UIImage imageNamed:@"后退按钮"] style:UIBarButtonItemStylePlain target:self action:@selector(fanhuishangyigejiemian)];
    backItem.tintColor = [UIColor blackColor];
    self.navigationItem.leftBarButtonItem = backItem;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:0 target:self action:@selector(shanchushipingEventClick)];
    [self responseNamed:@"" inBundle:nil];
}
-(void)responseNamed:(NSString*)responseName
                    inBundle:(nullable NSBundle*)responsesBundle
{
    NSURL *responseURL = [responsesBundle?:[NSBundle bundleForClass:self.class] URLForResource:responseName
                                                                                   withExtension:@"response"];

    NSData *responseData = [NSData dataWithContentsOfURL:responseURL];
//    NSAssert(responseData, @"Could not find HTTP response named '%@' in bundle '%@'", responseName, responsesBundle);
}

-(void)fanhuishangyigejiemian
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)jiemiandajianEventClick{
    [self.collectionView registerClass:XTXAlbumOrVideoCell.class forCellWithReuseIdentifier:NSStringFromClass(XTXAlbumOrVideoCell.class)];
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.tianjiaanniu];
    [self.view addSubview:self.wuneirongImageView];
    [self.view addSubview:self.wuneirongLabel];
    imgPicker = [[UIImagePickerController alloc]init];
    imgPicker.view.backgroundColor = [UIColor orangeColor];
    imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imgPicker.mediaTypes =  [[NSArray alloc] initWithObjects: @"public.movie", nil];
    imgPicker.delegate = self;
    imgPicker.allowsEditing = YES;
    [self getFileSize:@""];
}
-(CGFloat)getFileSize:(NSString *)filePath {
    CGFloat fileSize = 0.0;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        NSError *error;
        NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:filePath error:&error];
        if (nil != fileAttributes) {
            fileSize = [[fileAttributes objectForKey:NSFileSize] floatValue];
        }
    }
    return fileSize;
}
-(void)jiemianbujuEventClick
{
    _tianjiaanniu.sd_layout.widthIs(pingmuKuan).heightIs(60).centerXEqualToView(self.view).bottomSpaceToView(self.view, 0);
    if (liuhaiping) {
        _tianjiaanniu.sd_layout.widthIs(pingmuKuan).heightIs(60).centerXEqualToView(self.view).bottomSpaceToView(self.view, 20);
        
    }
    _wuneirongLabel.sd_layout.heightIs(13).bottomSpaceToView(self.view, 200.0).rightSpaceToView(self.view, 0).leftSpaceToView(self.view, 0);
    _wuneirongImageView.sd_layout.widthIs(220).heightIs(220).centerXEqualToView(self.view).bottomSpaceToView(_wuneirongLabel, 25.0);
    _wuneirongImageView.hidden = YES;
    _wuneirongLabel.hidden = YES;
    [self diskOfAllSizeMBytes];
}
- (CGFloat)diskOfAllSizeMBytes{
    CGFloat size = 0.0;
    NSError *error;
    NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
    if (error) {
#ifdef DEBUG
        NSLog(@"error: %@", error.localizedDescription);
#endif
    }else{
        NSNumber *number = [dic objectForKey:NSFileSystemSize];
        size = [number floatValue]/1024/1024;
    }
    return size;
}

- (void)shangchuangshipingshijianClick:(NSData *)data
{
    WeakSelf
    [XTXNetworking networkingUpUseShipinViewdewangluoqingqiu:data completionHandler:^(NSDictionary * _Nonnull dict) {
        if ([dict[@"code"] integerValue] == 1) {
            [weakSelf tianjiashipingshijianEventClick:dict[@"info"][@"videoUrl"]];
        }
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self->progreHud hideAnimated:YES afterDelay:0.2];
                [XTXGongView showTipMsg:dict[@"msg"]];
            });
        }
    }];
    [self diskOfFreeSizeMBytes];
}
-(CGFloat)diskOfFreeSizeMBytes{
    CGFloat size = 0.0;
    NSError *error;
    NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
    if (error) {
#ifdef DEBUG
        NSLog(@"error: %@", error.localizedDescription);
#endif
    }else{
        NSNumber *number = [dic objectForKey:NSFileSystemFreeSize];
        size = [number floatValue]/1024/1024;
    }
    return size;
}
- (void)tianjiashipingshijianEventClick:(NSString *) imageUrl
{
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    NSString *timeString = [NSString stringWithFormat:@"%.0lf", a];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"user_id"] = XTXGongTool.share.useMode.id;
    parameters[@"video"] = imageUrl;
    parameters[@"videoUrl"] = [NSString stringWithFormat:@"showPlace/%@/%@_video",XTXGongTool.share.useMode.id,timeString];
    parameters[@"user_idnum"] = XTXGongTool.share.useMode.idnum;
    WeakSelf
    [XTXNetworking networkingAddUsePlacedewangluoqingqiu:parameters.copy completionHandler:^(NSDictionary * _Nonnull dict) {
        if ([dict[@"code"] isEqualToString:@"1"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    self->pagInt1 = 0;
                    [weakSelf.videoArr removeAllObjects];
                    [weakSelf tishiliebiao];//列表
                });
            });
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self->progreHud hideAnimated:YES afterDelay:0.2];
            [XTXGongView showTipMsg:dict[@"msg"]];
        });
    }];
    [self firstCharacterWithString:@""];
}

- (NSString *)firstCharacterWithString:(NSString *)string{
    NSMutableString *str = [NSMutableString stringWithString:string];
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
    NSString *pingyin = [str capitalizedString];
    return [pingyin substringToIndex:1];
}


-(void)tanchushipingxuanzechuangkoushijianClick
{
    [self dictionaryOrderByCharacterWithOriginalArray:@[]];
    [self presentViewController:imgPicker animated:YES completion:nil];
}
-(NSDictionary *)dictionaryOrderByCharacterWithOriginalArray:(NSArray *)array{
    if (array.count == 0) {
        return nil;
    }
    for (id obj in array) {
        if (![obj isKindOfClass:[NSString class]]) {
            return nil;
        }
    }
    UILocalizedIndexedCollation *indexedCollation = [UILocalizedIndexedCollation currentCollation];
    NSMutableArray *objects = [NSMutableArray arrayWithCapacity:indexedCollation.sectionTitles.count];
    //创建27个分组数组
    for (int i = 0; i < indexedCollation.sectionTitles.count; i++) {
        NSMutableArray *obj = [NSMutableArray array];
        [objects addObject:obj];
    }
    NSMutableArray *keys = [NSMutableArray arrayWithCapacity:objects.count];
    //按字母顺序进行分组
    NSInteger lastIndex = -1;
    for (int i = 0; i < array.count; i++) {
        NSInteger index = [indexedCollation sectionForObject:array[i] collationStringSelector:@selector(uppercaseString)];
        [[objects objectAtIndex:index] addObject:array[i]];
        lastIndex = index;
    }
    //去掉空数组
    for (int i = 0; i < objects.count; i++) {
        NSMutableArray *obj = objects[i];
        if (obj.count == 0) {
            [objects removeObject:obj];
        }
    }
    //获取索引字母
    for (NSMutableArray *obj in objects) {
        NSString *str = obj[0];
        NSString *key = [self firstCharacterWithString:str];
        [keys addObject:key];
    }
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:objects forKey:keys];
    return dic;
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [self dismissViewControllerAnimated:YES completion:nil];
    _shipingUrl = [info objectForKey:UIImagePickerControllerMediaURL];
    if ([self jisuanYasuoDaxiao:_shipingUrl]<=20.0) {
        progreHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        progreHud.mode = MBProgressHUDModeIndeterminate;
        progreHud.label.text = @"正在上传...";
        progreHud.removeFromSuperViewOnHide = YES;
        NSData *videoData = [NSData dataWithContentsOfURL:_shipingUrl];
        [self shangchuangshipingshijianClick:videoData];
    }else{
        [XTXGongView showTipMsg:@"视频文件太大，请从新先选择！"];
        [self currentDateWithFormat:@""];
    }
}
-(NSString *)currentDateWithFormat:(NSString *)format{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    return [dateFormatter stringFromDate:[NSDate date]];
}
-(void)genjusuoyinbofangduiyingdeshipingEventClick:(NSInteger)index {
    XTXVideoModel *model=_videoArr[index];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:model.video]) {
        //有缓存直接播放
        NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[[NSUserDefaults standardUserDefaults] objectForKey:model.video]];
        self.videoUrl = fullPath;
        self.playerVC = [[AVPlayerViewController alloc] init];
            self.playerVC.player = [AVPlayer playerWithURL:[self.videoUrl hasPrefix:@"http"] ? [NSURL URLWithString:self.videoUrl]:[NSURL fileURLWithPath:self.videoUrl]];
            self.playerVC.view.frame = self.view.bounds;
            self.playerVC.showsPlaybackControls = YES;
        if (@available(iOS 11.0, *)) {
            self.playerVC.entersFullScreenWhenPlaybackBegins = YES;
        } else {
        }//开启这个播放的时候支持（全屏）横竖屏哦
        if (@available(iOS 11.0, *)) {
            self.playerVC.exitsFullScreenWhenPlaybackEnds = YES;
        } else {
        }//开启这个所有 item 播放完毕可以退出全屏
        if (self.playerVC.readyForDisplay) {
            [self.playerVC.player play];
        }
        [self presentViewController:self.playerVC animated:YES completion:nil];
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            self->progreHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            self->progreHud.mode = MBProgressHUDModeIndeterminate;
            self->progreHud.label.text= @"正在加载...";
            self->progreHud.removeFromSuperViewOnHide = YES;
        });
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:model.video]];
        NSURLSessionDownloadTask *download = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"YYYYMMddHHMMssSSS"];
            self->timeString = [dateFormatter stringFromDate:[NSDate date]];
            //保存的文件路径
            NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4",self->timeString]];
            return [NSURL fileURLWithPath:fullPath];
        } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
            [self->progreHud hideAnimated:YES afterDelay:0.1];
            [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%@.mp4",self->timeString] forKey:model.video];
            self.playerVC = [[AVPlayerViewController alloc] init];
            self.playerVC.player = [AVPlayer playerWithURL:filePath];
            self.playerVC.view.frame = self.view.bounds;
            self.playerVC.showsPlaybackControls = YES;
            if (@available(iOS 11.0, *)) {
                self.playerVC.entersFullScreenWhenPlaybackBegins = YES;
            } else {
                // Fallback on earlier versions
            }//开启这个播放的时候支持（全屏）横竖屏哦
            if (@available(iOS 11.0, *)) {
                self.playerVC.exitsFullScreenWhenPlaybackEnds = YES;
            } else {
                // Fallback on earlier versions
            }//开启这个所有 item 播放完毕可以退出全屏
            if (self.playerVC.readyForDisplay) {
                [self.playerVC.player play];
            }
            [self presentViewController:self.playerVC animated:YES completion:nil];
            
        }];
        
        //执行Task
        [download resume];
        [self timeIntervalFromLastTime:@"" lastTimeFormat:@"" ToCurrentTime:@"" currentTimeFormat:@""];
    }
    
}
- (void)timeIntervalFromLastTime:(NSString *)lastTime
                        lastTimeFormat:(NSString *)format1
                         ToCurrentTime:(NSString *)currentTime
                     currentTimeFormat:(NSString *)format2{
    //上次时间
    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
    dateFormatter1.dateFormat = format1;
    NSDate *lastDate = [dateFormatter1 dateFromString:lastTime];
    //当前时间
    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init];
    dateFormatter2.dateFormat = format2;
    [dateFormatter2 dateFromString:currentTime];
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (temInt0==1) {
        //取出对应的模型及cell
        XTXAlbumOrVideoCell *cell=(XTXAlbumOrVideoCell *)[collectionView cellForItemAtIndexPath:indexPath];
        XTXVideoModel *model=_videoArr[indexPath.item];
        //改变按钮的状态
        cell.deleteBtn.selected=!cell.deleteBtn.isSelected;
        if (cell.deleteBtn.isSelected) {//选中状态。添加sid到数组
            [self.deleteArr addObject:model.sid];
        }else{
            [self.deleteArr removeObject:model.sid];
        }
    }else{
        [self genjusuoyinbofangduiyingdeshipingEventClick:indexPath.row];
        [self timeIntervalFromLastTime:[NSDate date] ToCurrentTime:[NSDate date]];
    }
    
    
}
-(NSString *)timeIntervalFromLastTime:(NSDate *)lastTime ToCurrentTime:(NSDate *)currentTime{
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    //上次时间
    NSDate *lastDate = [lastTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:lastTime]];
    //当前时间
    NSDate *currentDate = [currentTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:currentTime]];
    //时间间隔
    NSInteger intevalTime = [currentDate timeIntervalSinceReferenceDate] - [lastDate timeIntervalSinceReferenceDate];
    
    //秒、分、小时、天、月、年
    NSInteger minutes = intevalTime / 60;
    NSInteger hours = intevalTime / 60 / 60;
    NSInteger day = intevalTime / 60 / 60 / 24;
    NSInteger month = intevalTime / 60 / 60 / 24 / 30;
    NSInteger yers = intevalTime / 60 / 60 / 24 / 365;
    //单位为分钟
    if (minutes <= 10) {
        return  @"刚刚";
    }else if (minutes < 60){
        return [NSString stringWithFormat: @"%ld分钟前",(long)minutes];
    }else if (hours < 24){
        return [NSString stringWithFormat: @"%ld小时前",(long)hours];
    }else if (day < 30){
        return [NSString stringWithFormat: @"%ld天前",(long)day];
    }else if (month < 12){
        NSDateFormatter * df =[[NSDateFormatter alloc]init];
        df.dateFormat = @"M月d日";
        NSString * time = [df stringFromDate:lastDate];
        return time;
    }else if (yers >= 1){
        NSDateFormatter * df =[[NSDateFormatter alloc]init];
        df.dateFormat = @"yyyy年M月d日";
        NSString * time = [df stringFromDate:lastDate];
        return time;
    }
    return @"";
}
-(void)shanchushipingEventClick{
    if (temInt0==1) {
        if (_deleteArr.count==0) {
            [XTXGongView showTipMsg:@"至少选中一个!"];
            [self colorWithHexString:@"#238592"];
        }else{
            for (NSString *uuid in self.deleteArr) {
                [self shanchushipingdewangluoqingqiu:uuid];
            }
            
        }
    }
}
-(UIColor *)colorWithHexString:(NSString *)color{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    // strip "0X" or "#" if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    //r
    NSString *rString = [cString substringWithRange:range];
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}

-(void)shanchushipingdewangluoqingqiu:(NSString *)uuid{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"user_id"] = XTXGongTool.share.useMode.id;
    parameters[@"id"] = uuid;
    WeakSelf
    [XTXNetworking networkingshanchushipingdeyaoqiu:parameters.copy completionHandler:^(NSDictionary * _Nonnull dict) {
        if ([dict[@"code"] isEqualToString:@"1"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.navigationItem.rightBarButtonItem.title = @"";
                //退出删除界面
                self->temInt0=0;
                [self.deleteArr removeAllObjects];
                [self.collectionView reloadData];
                [weakSelf.collectionView.mj_header beginRefreshing];
            });
        }else{
            [self filterWithOriginalImage:imageNamed(@"iconImage6") filterName:@""];
        }
    }];
}
-(UIImage *)filterWithOriginalImage:(UIImage *)image filterName:(NSString *)name{
    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage *inputImage = [[CIImage alloc] initWithImage:image];
    CIFilter *filter = [CIFilter filterWithName:name];
    [filter setValue:inputImage forKey:kCIInputImageKey];
    CIImage *result = [filter valueForKey:kCIOutputImageKey];
    CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];
    UIImage *resultImage = [UIImage imageWithCGImage:cgImage];
    CGImageRelease(cgImage);
    return resultImage;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _videoArr.count;
}
-(UIImage *)blurWithOriginalImage:(UIImage *)image blurName:(NSString *)name radius:(NSInteger)radius{
    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage *inputImage = [[CIImage alloc] initWithImage:image];
    CIFilter *filter;
    if (name.length != 0) {
        filter = [CIFilter filterWithName:name];
        [filter setValue:inputImage forKey:kCIInputImageKey];
        if (![name isEqualToString:@"CIMedianFilter"]) {
            [filter setValue:@(radius) forKey:@"inputRadius"];
        }
        CIImage *result = [filter valueForKey:kCIOutputImageKey];
        CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];
        UIImage *resultImage = [UIImage imageWithCGImage:cgImage];
        CGImageRelease(cgImage);
        return resultImage;
    }else{
        return nil;
    }
}
-(void)longPressGestEvetn:(UILongPressGestureRecognizer*)ges{
    if(ges.state==UIGestureRecognizerStateBegan){
        if (temInt0==0) {
            self.navigationItem.rightBarButtonItem.title = @"删除";
            temInt0=1;
            [_collectionView reloadData];
        }else{
            self.navigationItem.rightBarButtonItem.title = @"";
            temInt0=0;
            [_collectionView reloadData];
            [self blurWithOriginalImage:imageNamed(@"iconImage7") blurName:@"" radius:0];
        }
        
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    XTXAlbumOrVideoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass(XTXAlbumOrVideoCell.class) forIndexPath:indexPath];
    cell.backgroundColor = [UIColor lightGrayColor];
    XTXVideoModel *model=_videoArr[indexPath.item];
    [cell.pictureImageView sd_setImageWithURL:[NSURL URLWithString:model.image]];
    if (temInt0==1) {
        cell.deleteBtn.hidden = NO;
        cell.deleteBtn.selected = NO;
    }else{
        cell.deleteBtn.hidden = YES;
        [self colorControlsWithOriginalImage:imageNamed(@"iconImage8") saturation:0 brightness:0 contrast:0];
    }
    UILongPressGestureRecognizer* longgs=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressGestEvetn:)];
    [cell addGestureRecognizer:longgs];//为cell添加手势
    longgs.minimumPressDuration=0.5;//定义长按识别时长
    longgs.view.tag=indexPath.row;//将手势和cell的序号绑定
    return cell;
}
-(UIImage *)colorControlsWithOriginalImage:(UIImage *)image
                                 saturation:(CGFloat)saturation
                                 brightness:(CGFloat)brightness
                                   contrast:(CGFloat)contrast{
    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage *inputImage = [[CIImage alloc] initWithImage:image];
    CIFilter *filter = [CIFilter filterWithName:@"CIColorControls"];
    [filter setValue:inputImage forKey:kCIInputImageKey];
    
    [filter setValue:@(saturation) forKey:@"inputSaturation"];
    [filter setValue:@(brightness) forKey:@"inputBrightness"];
    [filter setValue:@(contrast) forKey:@"inputContrast"];
    
    CIImage *result = [filter valueForKey:kCIOutputImageKey];
    CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];
    UIImage *resultImage = [UIImage imageWithCGImage:cgImage];
    CGImageRelease(cgImage);
    [self effectViewWithFrame:CGRectMake(0, 0, 0, 0)];
    return resultImage;
}
-(UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayOut = [[UICollectionViewFlowLayout alloc] init];
        flowLayOut.itemSize = CGSizeMake((pingmuKuan - 50)/ 3, 140);
        flowLayOut.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
        self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, pingmuKuan, pingmuGao-80) collectionViewLayout:flowLayOut];
        _collectionView.backgroundColor  = rgbYanse1(0xf5f5f5);
        self.collectionView.delegate = self;
        self.collectionView.dataSource = self;
    }
    return _collectionView;
}
-(UIVisualEffectView *)effectViewWithFrame:(CGRect)frame{
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
    effectView.frame = frame;
    return effectView;
}
- (UIButton *)tianjiaanniu{
    if (!_tianjiaanniu) {
        self.tianjiaanniu = [UIButton buttonWithType:UIButtonTypeCustom];
        [_tianjiaanniu setTitle:@"上传自拍视频" forState:UIControlStateNormal];
        _tianjiaanniu.backgroundColor = rgbYanse1(0x9446ff);
        [_tianjiaanniu addTarget:self action:@selector(tanchushipingxuanzechuangkoushijianClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _tianjiaanniu;
}
-(UIImageView *)wuneirongImageView{
    if (!_wuneirongImageView) {
        _wuneirongImageView = [UIImageView new];
        _wuneirongImageView.image = [UIImage imageNamed:@"无内容图片"];
    }
    return _wuneirongImageView;
}
-(UIImage *)shotScreen{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIGraphicsBeginImageContext(window.bounds.size);
    [window.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
-(UILabel *)wuneirongLabel{
    if (!_wuneirongLabel) {
        _wuneirongLabel = [UILabel new];
        _wuneirongLabel.font = [UIFont systemFontOfSize:14];
        _wuneirongLabel.textColor = rgbYanse1(0xc8c8c8);
        _wuneirongLabel.textAlignment = NSTextAlignmentCenter;
        _wuneirongLabel.text = @"还没有上传自拍视频";
    }
    return _wuneirongLabel;
}
//计算压缩大小
- (CGFloat)jisuanYasuoDaxiao:(NSURL *)path
{
    if (!self.view) {
        [self shotScreen];
    }
    return [[NSData dataWithContentsOfURL:path] length]/1024.00 /1024.00;
}

@end
